$(function () {

    var alertUI = (function () {
        var timer;
        var $alertTips = $('#alertTips');
        var $alertTipsInner = $('#alertTipsInner');

        function init(text, time) {
            var time = time || 1000;

            clearTimeout(timer);
            $alertTipsInner[0].innerHTML = text;
            $alertTips.show();
            timer = setTimeout(function () {
                $alertTips.hide();
            }, time);

        }

        return {
            init: init
        }


    }());

    /**
     * ============================================================================
     * toggle
     * ============================================================================
     */
    var toggle = (function ($) {

        function toggleFun($self, other) {
            var show = false;
            var $parent = $self.parent();

            if (!$parent.hasClass("active")) {
                show = true;
            }

            $(other).removeClass("active");

            if (show) {
                $parent.addClass("active");
            }
        }

        $("body").on("click", "[data-toggle='toggle']", function (e) {
            e.preventDefault();

            var $self = $(this);
            var other = $self.attr("data-toggle-box");

            toggleFun($self, other);
        });

        return {
            toggleFun: toggleFun
        };

    }(Zepto));


    /**
     * ============================================================================
     * 获取数据
     * ============================================================================
     */
    var modelModule = (function () {
        var numberPicker;
        var dataUrl = UrlInformation.apipath+'/common/ProductInfoCtrl/getProductInfoById';
        //doT模板
        function dataCallback(json, $tmpl, $appedEL, fn) {

            $appedEL[0].innerHTML = doT.compile($tmpl[0].innerHTML)(json);

            fn && fn();
        }

        //根据数据更新UI
        function formateValue(original, title, number) {
            var valueArray = new Array();
            var unit = original.match(/\D+$/);
            var value = original.replace(/[\u4E00-\u9FA5]/, "");
            $(number).html(value);
            if (unit != undefined || unit != "") {
                $(title).html($(title).html() + "(" + unit + ")");
            }
        }

        //显示隐藏提示
        function labelOperation(info) {
            $('#checkInfo').html(info);
        }

        //输入框绑定事件
        //最小收益率
        //最大收益率
        //最小递增数
        //期限（天）
        //回调函数
        function bindInputEvent(minYearRate,maxYearRate,minAppendAccount,days,subscriptionOrigin,changeMoneyAccount){
            $('#moneyAccount').on('input',function(){
                $(this).val(this.value.replace(/\D/g,''));
                var money;
                //输入框值为0时隐藏slider
                if(this.value==''){
                    $('#slider').css('display','block');
                    money=$('#slider .swiper-slide-active').attr('valueNum');
                }
                else {
                    $('#slider').css('display','none');
                     money = parseInt(this.value);
                }

                //计算最终值
                if (money > 100000000) {
                    return;
                }
                if(money % minAppendAccount != 0||money < subscriptionOrigin) {
                    if (money % minAppendAccount != 0) {
                        labelOperation('投资金额必须为' + minAppendAccount + '的整倍数');
                    }
                    if (money < subscriptionOrigin) {
                        labelOperation('投资金额必须大于等于' + subscriptionOrigin + '元');
                    }
                }
                else{
                    labelOperation('');
                }


                operateObj = GetFormatResult.getProfitResult(days, minYearRate, maxYearRate);
                var minResult = operateObj.min(money);
                var maxResult = operateObj.max(money);
                changeMoneyAccount(minResult, maxResult);

            });

            //阻止事件冒泡，防止下层div干扰
            $('#isGetCard').on('click',function(event){
                if(event.stopPropagation) {
                    event.stopPropagation();
                }
                else{
                    event.cancelBubble=true;
                }
            });

            $('#agreeMentLink').on('click',function(event){
               /* var params = {
                    'curPage' : 1,
                    'pageSize' : 99999,
                    'name' : '债权及收益权转让和服务协议'
                };
                commonAjax(UrlInformation.apipath+ '/common/agreementCtrl/list',JSON.stringify(params),function(data){
                    var result=JSON.parse(data);
                    layer.open({
                        type: 1,
                        shadeClose: false,
                        content: '<div style="margin: 5% 0 5% 0;padding: 0 5% 0 5%;position:absolute; height: 85%;overflow: scroll;border-bottom-style: solid;border-width: 1px;border-color: lightgray;">'+result.result[0].agreementText+'</div><div style="text-align: center;position: absolute;bottom: 1%;width: 100%; height: 6%;"><button onclick="layer.closeAll();"  style="border-style: solid;border-radius: 5px;background-color: transparent;width: 20%; height: 100%;height: 80%;font-size: 0.7rem;">关闭</button></div>',
                        anim: 0,
                        style: 'position:fixed; bottom:0; left:5%;top:10%; width:90%; height:80%; padding:10px 0; border:none;border-radius: 6px;'
                    });
                });*/

                $.ajax({
                    url: UrlInformation.apipath+'/common/agreementCtrl/getById?strId=79225112718646',
                    type: "GET",
                    contentType: 'application/json',
                    success: function(data){
                        var result=JSON.parse(data);
                        layer.open({
                            type: 1,
                            shadeClose: false,
                            content: '<div style="margin: 5% 0 5% 0;padding: 0 5% 0 5%;position:absolute; height: 85%;overflow: scroll;border-bottom-style: solid;border-width: 1px;border-color: lightgray;">'+result.result+'</div><div style="text-align: center;position: absolute;bottom: 1%;width: 100%; height: 6%;"><button onclick="layer.closeAll();"  style="border-style: solid;border-radius: 5px;background-color: transparent;width: 20%; height: 100%;height: 80%;font-size: 0.7rem;">关闭</button></div>',
                            anim: 0,
                            style: 'position:fixed; bottom:0; left:5%;top:10%; width:90%; height:80%; padding:10px 0; border:none;border-radius: 6px;'
                        });
                    },
                    error: function (error) {
                        alert(error);
                    }
                });
            });

        }
        //卡券绑定点击事件
        function bindCardEvents(){
            $('.card').on('click',function(event){
                $('.card').removeClass('activeColor');
                var target=$(event.target || event.srcElement);
                var card;
                if($(target).attr('class').indexOf('card')<0){
                    card=$(target).parents('.card');
                    //$(target).parents('.card').addClass('activeColor')
                }
                else{
                    card=$(event.target || event.srcElement);
                    //$(event.target || event.srcElement).addClass('activeColor');
                }
                $(card).addClass('activeColor');
                $('#cardMessage').html($(card).children('.desc').html());
                $('#isGetCard').attr('cardId',$(card).attr('cardId'));
                //jquery用atrr有问题
                document.getElementById('isGetCard').checked=true;
               // $('#isGetCard').attr("checked","checked");
                openFunction.getCard();
            })
        }

        //改变总收益
        function changeMoneyAccount(minResult, maxResult){
            if(parseInt(minResult)!=minResult){
                minResult=minResult.toFixed(2)
            }
            if(parseInt(maxResult)!=maxResult){
                maxResult=maxResult.toFixed(2)
            }
            if (minResult == maxResult) {
                $('#profitResult').html(minResult);
            }
            else {
             /*   $('#profitResult').html(formatMoney(minResult,0) + '～' + formatMoney(maxResult,0));*/
                $('#profitResult').html(formatMoney(minResult,0) + '～' + formatMoney(maxResult,0));
            }
        }

        function getData() {
            var data = {
                'id': wxUtils.getParamsByUrl('id')
            };
            $.ajax({
                type: 'POST',
                url: dataUrl,
                contentType: 'application/json',
                data: JSON.stringify(data),
                dataType: 'json',
                success: function (json) {
                    if (json.resultCode == '200') {
                        var result = json.result;
                        //获取数字选择器数字组合
                         numberPicker = new numberpicker(result.proTerm,result.minYearRate, result.maxYearRate, changeMoneyAccount);
                        //初始化所有的数字选项
                        var numberArray = numberPicker.getNumbersByRange(result.subscriptionOrigin, result.financingAccount, result.minAppendAccount);
                        var pickerInstance= numberPicker.initNumberBar(numberArray);

                        bindInputEvent(result.minYearRate, result.maxYearRate,result.minAppendAccount,result.proTerm,result.subscriptionOrigin, changeMoneyAccount);

                        //根据最小递增量动态改变提示语句
                        $('#moneyAccount').attr('placeholder','请输入'+ formatMoney(result.minAppendAccount,0)+'的整倍数');
                        //预期收益率
                        var incomeRate = getDescByCode.getIncomeRate(result.minYearRate,result.maxYearRate);
                        //浮动收益隐藏收益助手
                        if(incomeRate=='浮动'){
                            $('#profitAssistant').hide();
                        }

                        $('#incomeRate').html(incomeRate);
                        //风险等级
                        var riskClass = getDescByCode.getRiskClass(result.riskLevel);
                        for(var i=0;i<=riskClass.riskNumber;i++) {
                            (function (a) {
                                setTimeout(function () {
                                    $('#riskDiv').children('.smallCircle').eq(a).addClass(riskClass.riskDictionary[a]);
                                }, (a + 1) * 100);

                                if (a != riskClass.riskNumber) {
                                    setTimeout(function () {
                                        $('#riskDiv').children('.smallCircle').eq(a).removeClass(riskClass.riskDictionary[a]);
                                    }, (a + 1) * 100+500);
                                }
                            })(i);
                        }

                      /*  $('#riskDiv').children('.smallCircle').eq(riskClass.riskNumber).addClass(riskClass.riskStyle);*/
                        $('#riskDiv').children('.greyTitle').eq(riskClass.riskNumber).addClass(riskClass.riskStyle + ' transparentBackground');
                        $('#riskLevel').html(getDescByCode.getRiskLevel(result.riskLevel));

                        var subscriptionOrigin = getDescByCode.getAccouountVal(result.subscriptionOrigin);
                       /* var subscriptionOrigin = getDescByCode.getAccouountVal(1000);*/
                        $('#subscriptionOrigin').html(subscriptionOrigin);
                        $('#subscriptionOrigin').attr('subscriptionOrigin',result.subscriptionOrigin);

                        /*formateValue(subscriptionOrigin,$('#mainTitle'),$('#subscriptionOrigin'));*/
                        //剩余额度
                        var sraiseAccount = getDescByCode.getAccouountVal(result.sraiseAccount);
                        $('#sraiseAccount').attr('sraiseAccount',result.sraiseAccount);
                        $('#sraiseAccount').html(sraiseAccount);
                        //formateValue(sraiseAccount, $('#greyTitle').children().eq(0), $('#sraiseAccount'));

                        // 期限
                        /*var proTerm = getDescByCode.getTerm(result.proTerm);*/
                        var proTerm = result.proTermStr;
                        $('#proTerm').html(proTerm);
                        $('#proTermForTitle').html('/'+proTerm)
                        // formateValue(proTerm, $('#greyTitle').children().eq(1), $('#proTerm'));

                        //总额
                        var financingAccount = getDescByCode.getAccouountVal(result.financingAccount);
                        $('#financingAccount').html(financingAccount);
                        //formateValue(financingAccount, $('#greyTitle').children().eq(2), $('#financingAccount'));

                        //进度
                        var ycount = result.yraiseAccount; //已募集的金额
                        var financingAccount = result.financingAccount;
                        var rate = '0%';
                        if (ycount == financingAccount) {
                            rate = '100%';
                        } else {
                            var num01 = (ycount / financingAccount).toFixed(4);
                            var rate = (num01 * 100).toFixed(2) + "%";
                        }
                        $('#percentTxt').html(rate);
                        $('#progress').css('width', rate);

                        //余额不足时直接隐藏所有输入窗口
                        if(parseFloat(result.sraiseAccount)<parseFloat(result.subscriptionOrigin)){
                            $('#profitAssistant').hide();
                          /*  layer.open({
                                content: '已售罄！',
                                btn: ['OK']
                            });*/
                        }

                        var json = {
                            title1: '收益说明书',
                            content1: result.incomeTxt,
                            title2: '产品自我介绍',
                            content2: result.introduceTxt,
                            title3: '产品的来龙去脉',
                            content3: {
                                c_title1: '【资金用途】',
                                c_content1: result.fundUse == null ? '' : result.fundUse,
                                c_title2: '【产品发行方式】',
                                c_content2: getDescByCode.getPublishType(result.publishType),
                                /*	c_title3: '【债权推荐方】',
                                 c_content3: result.claimRecommend==null?'':result.claimRecommend,
                                 c_title4: '【债权转让服务方】',
                                 c_content4: result.creditAssignment==null?'':result.creditAssignment,
                                 c_title5: '【债权转让服务方介绍】',
                                 c_content5: result.creditAssignmentInfo==null?'':result.creditAssignmentInfo,*/
                                c_title3: '【回款来源】',
                                c_content3: result.paymentSource == null ? '' : result.paymentSource,
                               /* c_title4: '【关联方介绍】',
                                c_content4: result.paymentSource == null ? '' : result.paymentSource,*/
                                /*c_title7: '【债权推荐方介绍】',
                                 c_content7: result.claimRecommendInfo==null?'':result.claimRecommendInfo*/
                            },
                            title4: '如何保证安全性',
                            content4: result.riskctrlTxt,
                            title5:'如何签约',
                            content5:result.signflowTxt==undefined?"":result.signflowTxt
                        };
                        dataCallback(json, $('#panelListTmpl'), $('#panelList'));
                    } else {
                        alertUI.init('网络繁忙，请稍后再试');
                    }
                },
                error: function () {
                    alertUI.init('网络繁忙，请稍后再试');
                }
            });
        }

        //获取卡券列表
        function getCardList(){
            var data = {
                'userId': wxUtils.getParamsByUrl('userid'),
                'status': 0
            };
            commonAjax(UrlInformation.apipath+'/app/userCardCtr/list',JSON.stringify(data),function(result){

                var data=JSON.parse(result);
                if(data.resultCode=='200') {
                    var template = _.template($('#cardTemp').html());
                    $('#cardList').append(template({results:data.result}));
                    bindCardEvents();
                }
                else {
                    alert(result.msg);
                }
            })
        }
        //根据支付渠道判断是否显示电子合同
        function showAgreeMentOrNot(){
            //1.5.1之后做版本兼容
            var version=wxUtils.getParamsByUrl('version');
            if(version>=1.51) {
                $('#agreeMent').hide();
            }
            var buyChannel=wxUtils.getParamsByUrl('buyChannel');
            if(buyChannel!=2){
                $('#agreeMent').hide();
            }
        }

        function init() {
            getData();
            showAgreeMentOrNot();
            //加息券暂时不展示
           // getCardList();
            var json = {
                title1: '年化收益率',
                content1: '',
                title2: '产品介绍',
                content2: '',
                title3: '产品要素',
                content3: '暂无',
                title4: '产品风控',
                content5: ''
            };
            dataCallback(json, $('#panelListTmpl'), $('#panelList'));
        }
        init();
    }());

});